<template>
	<view class="order-page">
		<!-- 订单状态页签 -->
		<view class="tabs-container">
			<u-tabs :list="tabs" :current="currentTab" @change="tabChange" :activeStyle="{color: '#ff2d51'}"
				:inactiveStyle="{color: '#666'}" lineColor="#ff2d51" :scrollable="true"></u-tabs>
		</view>

		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-list" :style="{height: scrollHeight + 'px'}" @scrolltolower="loadMore"
			refresher-enabled :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
			<!-- 订单卡片 -->
			<view v-for="(order, index) in List" :key="order.id" class="order-card">
				<!-- 订单头部 -->
				<view class="order-header">
					<text class="order-no">订单号：{{order.orderNo}}</text>
					<text class="order-status" :style="{color: getStatusColor(order.status)}">
						{{order.statusText}}
					</text>
				</view>

				<!-- 订单商品 -->
				<view class="order-goods" v-for="(goods, gIndex) in order.goodsList" :key="gIndex"
					@click="goOrderDetail(order.id)">
					<u-image :src="goods.goodsImage" width="140rpx" height="140rpx" radius="8"></u-image>
					<view class="goods-info">
						<view class="goods-name">{{goods.goodsName}}</view>
						<view class="goods-spec">规格：{{goods.spec}}</view>
						<view class="goods-price">
							<text>¥{{goods.price}}</text>
							<text class="goods-count">x{{goods.count}}</text>
						</view>
					</view>
				</view>

				<!-- 订单底部 -->
				<view class="order-footer">
					<view class="order-total">
						共{{order.goodsList.length}}件商品 合计：<text class="total-price">¥{{order.totalAmount}}</text>
					</view>

					<view class="order-actions">
						<u-button v-if="order.status === 1" size="mini" type="error" @click="cancelOrder(order.id,index)"
							shape="circle">取消订单</u-button>

						<u-button v-if="order.status === 2" size="mini" type="error" @click="applyaftersales(order.id)"
							shape="circle">申请售后</u-button>
						<u-button v-if="order.status === 2" size="mini" type="warning" @click="viewlogsitc(order.id)"
							shape="circle">查看物流</u-button>
						<u-button v-if="order.status === 2" size="mini" type="primary"
							@click="confirmReceipt(order.id,index)" shape="circle">确认收货</u-button>

						<u-button v-if="order.status === 3 && !order.hasAfterSale && order.isclose===0" size="mini"
							type="error" @click="applyaftersales(order.id)" shape="circle">申请售后</u-button>
						<u-button v-if="order.status === 3 && !order.hasAfterSale" type="primary" size="mini"
							shape="circle" text="再次购买" @click="goOrderDetail(order['goodsList'][0]['goodsId'])"></u-button>

						<u-button v-if="(order.status === 3 && order.hasAfterSale)||order.status === 4" size="mini"
							type="error" @click="goAfterSaleDetail(order.afterSaleId)" shape="circle">查看售后</u-button>
					</view>
				</view>
			</view>

			<!-- 加载状态 -->
			<u-loadmore :status="loadStatus" :icon-type="loadStatus === 'loading' ? 'circle' : 'none'" />

			<!-- 空状态 -->
			<u-empty v-if="List.length === 0 && !loading" mode="order" :text="emptyText"></u-empty>
			<!--         icon="http://cdn.uviewui.com/uview/empty/order.png" -->
		</scroll-view>
	</view>
</template>

<script>
	import {
		httpsend
	} from '@/api/api';
	export default {
		data() {
			return {
				currentTab: 0,
				tabs: [{
						name: '全部'
					},
					{
						name: '待发货'
					},
					{
						name: '待收货'
					},
					{
						name: '已完成'
					},
					{
						name: '售后'
					}
				],
				scrollHeight: 0,
				List: [],
				loading: false,
				loadStatus: 'loadmore',
				refreshing: false,
				page: 1,
				pageSize: 10,
				hasMore: true
			}
		},
		computed: {
			emptyText() {
				return this.currentTab === 4 ? '暂无售后订单' : '暂无订单';
			}
		},
		onLoad(options) {
			if (options.tab) {
				this.currentTab = parseInt(options.tab) || 0;
			}
			this.calcScrollHeight();
			this.getList();
		},
		onPullDownRefresh() {
			this.onRefresh();
		},
		methods: {
			calcScrollHeight() {
				const systemInfo = uni.getSystemInfoSync();
				this.scrollHeight = systemInfo.windowHeight;  
			},

			// 获取订单列表
			async getList() {

				try {
					this.loading = true;
					this.loadStatus = 'loading';
					let param = {
						usrid: uni.getStorageSync('usrid'),
						type: this.currentTab,
						page: this.page,
						pageSize: this.pageSize
					}
					uni.showLoading({
						title: '加载中...'
					});
					const res = await httpsend('getmyorder', JSON.stringify(param));
					if (res?.code === 1) {
						//商品订单信息
						if (this.page == 1) {
							this.List = res.data;
						} else {
							this.List = [...this.List, ...res.data];
						}
						//实际接口注释掉 1 待发货 2待收货 3已完成 4售后处理中
						if(this.currentTab!==0){
							this.List=this.List.filter(item=>item.status==this.currentTab);
						}
					} else {
						this.$api.msg(res.msg);
					}
					this.loading = false;
					uni.hideLoading();
					this.page++;
					// 模拟分页结束
					if (this.page >= 3) {
						this.hasMore = false;
						this.loadStatus = 'nomore';
					} else {
						this.loadStatus = 'loadmore';
					}
				} catch (err) {
					this.loading = false;
					uni.hideLoading();
					console.log('err', err);
				}
			},
			// 切换标签
			tabChange(item) {
				this.currentTab = item.index;
				this.page = 1;
				this.hasMore = true;
				this.List = [];
				this.getList();
			},

			// 加载更多
			loadMore() {
				if (this.loadStatus === 'nomore') return;
				this.getList();
			},

			// 下拉刷新
			onRefresh() {
				this.refreshing = true;
				this.page = 1;
				this.hasMore = true;
				this.getList();
			},
			// 获取状态颜色
			getStatusColor(status) {
				// 0 已取消 1 待发货 2待收货 3已完成 4售后处理中
				const map = {
					0: '#999',
					1: '#ff2d51',
					2: '#ff9500',
					3: '#07c160',
					4: '#1989fa'
				};
				return map[status] || '#333';
			},

			// 跳转订单详情
			goOrderDetail(goodsid) {
				uni.navigateTo({
					url: `/pages/goodsinfo/goodsdetail?id=${goodsid}`
				});
			},
			// 取消订单
			async cancelOrder(orderId, index) {
				const res = await new Promise((resolve) => {
					uni.showModal({
						title: '提示',
						content: '确定要取消该订单吗?',
						success: (confirmRes) => {
							resolve(confirmRes.confirm);
						}
					});
				});
				if (!res) return;
				try {
					uni.showLoading({
						title: '正在取消...'
					});
					const res = await httpsend('cancelorder', JSON.stringify({
						usrid: uni.getStorageSync('usrid'),
						id: orderId
					}));
					if (res?.code === 1) {
						this.List[index]['status'] = 0;
						this.List[index]['statusText'] = '已取消';
					} else {
						this.$api.msg(res.msg);
					}
					uni.hideLoading();
				} catch (err) {
					uni.hideLoading();
					console.log('err', err);
				}
			},
			// 确认收货
			async confirmReceipt(orderId, index) {
				const res = await new Promise((resolve) => {
					uni.showModal({
						title: '提示',
						content: '请确认已收到商品，确认收货后款项将打给卖家',
						success: (confirmRes) => {
							resolve(confirmRes.confirm);
						}
					});
				});
				if (!res) return;
				
				try {
					uni.showLoading({
						title: '正在处理...'
					});
					const res = await httpsend('comfirmReceipt',JSON.stringify({
						usrid: uni.getStorageSync('usrid'),
						id: orderId
					}));
					if (res?.code === 1) {
						this.List[index].status = 3;
						this.List[index].statusText = '已完成';
					} else {
						this.$api.msg(res.msg);
					}
					uni.hideLoading();
				} catch (err) {
					uni.hideLoading();
					console.log('err', err);
				}
			},
			//申请售后
			applyaftersales(id) {
				uni.navigateTo({
					url: `/pages/order/aftersales?id=${id}`
				});
			},
			
			// 跳转售后详情
			goAfterSaleDetail(afterSaleId) {
				uni.navigateTo({
					url: `/pages/order/aftersalesdetail?id=${afterSaleId}`
				});
			},
			//查看物流
			viewlogsitc(id) {
				uni.navigateTo({
					url: `/pages/order/viewlogistic?id=${id}`
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.order-page {
		height: 100vh;
		background-color: #f7f7f7;
	}

	.tabs-container {
		background-color: #fff;
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.order-list {
		padding: 20rpx;
		box-sizing: border-box;
	}

	.order-card {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;

		.order-header {
			display: flex;
			justify-content: space-between;
			padding: 20rpx;
			border-bottom: 1rpx solid #f5f5f5;

			.order-no {
				font-size: 24rpx;
				color: #666;
			}

			.order-status {
				font-size: 24rpx;
				font-weight: bold;
			}
		}

		.order-goods {
			display: flex;
			padding: 20rpx;
			border-bottom: 1rpx solid #f5f5f5;

			.goods-info {
				flex: 1;
				margin-left: 20rpx;

				.goods-name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 10rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}

				.goods-spec {
					font-size: 24rpx;
					color: #999;
					margin-bottom: 10rpx;
				}

				.goods-price {
					display: flex;
					justify-content: space-between;
					font-size: 28rpx;
					color: #ff2d51;
					font-weight: bold;

					.goods-count {
						color: #666;
						font-weight: normal;
					}
				}
			}
		}

		.order-footer {
			padding: 20rpx;

			.order-total {
				text-align: right;
				font-size: 26rpx;
				color: #666;
				margin-bottom: 20rpx;

				.total-price {
					color: #ff2d51;
					font-weight: bold;
				}
			}

			.order-actions {
				display: flex;
				justify-content: flex-end;

				.u-button {
					margin-left: 20rpx;
				}
			}
		}
	}

	.load-status {
		padding: 20rpx 0;
	}

	/* uView 组件样式覆盖 */
	:deep(.u-tabs__wrapper__nav__item) {
		flex: none;
		padding: 0 20rpx;
	}

	:deep(.u-button) {
		min-width: 140rpx;
	}
</style>